package com.meta.nd.service.impl;

import com.meta.common.CommonInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import com.meta.common.ConstDef;
import com.meta.nd.service.ExecuteRuleService;
import com.meta.nd.service.NvBusinessService;
import com.meta.nd.service.NvService;
import com.meta.nd.vo.Nv;
import com.meta.rule.RuleRunContext;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@EnableTransactionManagement
@Transactional(rollbackFor = Exception.class)
@Component
@Service
public class NvBusinessServiceImpl implements NvBusinessService {
	
	@Autowired
	private NvService nvService;
	
	@Autowired
	private ExecuteRuleService executeRuleService;


	@Override
	public long commitNv(CommonInfo commonInfo, Nv nv){
		ArrayList<Nv> nvs = new ArrayList<>();
		nvs.add(nv);
		this.commitNvs(commonInfo,nvs);
		return nv.getId();
	}



@Override
public void commitNvs(CommonInfo commonInfo, List<Nv> nvs ){
	String transactionType = commonInfo.getTransactionType();
	if (StringUtils.isEmpty(transactionType))
		transactionType = ConstDef.TRANSACTION_TYPE_COMMIT;
	RuleRunContext context = new RuleRunContext();
	for( Nv nv : nvs) {
		if(ConstDef.OPERATION_FLAG_DELETE.equals(nv.getOperationFlag()))
			continue;
		executeRuleService.executeNvRule(transactionType, nv, context);
		if ( !context.isSuccess() || !context.isValid())
			throw new RuntimeException("保存实例执行规则有错 ：" + context.getMessageText());
	}
	nvService.internalSaveNvs(commonInfo,nvs);
}

}
